<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <!--主页图标-->
      <a-col flex="200px">
        <RouterLink to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/logo.png" alt="logo" />
            <div class="title">临昼笔记流</div>
          </div>
        </RouterLink>
      </a-col>
      <!--菜单导航栏-->
      <a-col flex="auto">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="items"
          @click="doMenuClick"
        />
      </a-col>
      <!--登录按钮or用户信息-->
      <a-col flex="220px">
        <div class="user-login-status">
          <div v-if="loginUserStore.loginUser.id">
            <a-space>
              <a-button type="link" @click="openMyNotes">
                <template #icon>
                  <FileTextOutlined />
                </template>
                我的笔记
              </a-button>
              <a-dropdown>
                <ASpace>
                  <a-avatar :src="loginUserStore.loginUser.userAvatar" />
                  {{ loginUserStore.loginUser.userName ?? '无名' }}
                </ASpace>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="goToProfile">
                      <UserOutlined />
                      我的资料
                    </a-menu-item>
                    <a-menu-item @click="doLogout">
                      <LogoutOutlined />
                      退出登录
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </div>

          <div v-else>
            <a-button type="primary" href="/user/login">登录</a-button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { computed, h, onMounted, ref } from 'vue'
import { HomeOutlined, FileTextOutlined, LogoutOutlined, UserOutlined } from '@ant-design/icons-vue'
import { type MenuProps, message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import checkAccess from '@/access/checkAccess'
import { routes } from '@/router/index'
import { userLogoutUsingPost } from '@/api/userController'

const router = useRouter()
const route = useRoute()
// 当前选中菜单
const current = ref<string[]>([])

// 初始化 current 为当前路由路径
onMounted(() => {
  current.value = [route.path]
})
// 监听路由变化，更新当前选中菜单
router.afterEach((to, from, next) => {
  current.value = [to.path]
})
// 菜单列表
const originItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  {
    key: '/admin/userManage',
    label: '用户管理',
    title: '用户管理',
  },
  {
    key: '/admin/categoryManage',
    label: '分类管理',
    title: '分类管理',
  },
  {
    key: '/addNote',
    label: '创建笔记',
    title: '创建笔记',
  },
  {
    key: '/admin/noteManage',
    label: '笔记管理',
    title: '笔记管理',
  },
]

// 过滤菜单项
/*const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    if (menu.key.startsWith('/admin')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}

// 展示在菜单的路由数组
const items = computed<MenuProps['items']>(() => filterMenus(originItems))*/

function menuToRouteItem(menu): MenuProps['items'][number] | null {
  console.log('Checking menu:', menu)
  const route = routes.find((route) => route.path === menu.key)
  console.log('Found route:', route)

  if (!route) {
    console.warn(`No route found for menu key: ${menu.key}`)
    return null
  }

  const menuItem: MenuProps['items'][number] = {
    key: route.path,
    label: route.name || menu.label,
    icon: menu.icon,
    meta: route.meta,
  }

  return menuItem
}

// 过滤菜单项
/*const items = menus.filter((menu) => {
  // todo 需要自己实现 menu 到路由 item 的转化
  const item = menuToRouteItem(menu)
  if (item.meta?.hideInMenu) {
    return false
  }
  // 根据权限过滤菜单，有权限则返回 true，则保留该菜单
  return checkAccess(loginUserStore.loginUser, item.meta?.access as string)
})*/

// 过滤菜单项
const items = computed<MenuProps['items']>(() => {
  console.log('Origin Items:', originItems)
  return originItems.flatMap((menu) => {
    const item = menuToRouteItem(menu)
    console.log('Converted Item:', item)
    if (
      item &&
      !item.meta?.hideInMenu &&
      checkAccess(loginUserStore.loginUser, item.meta?.access as string)
    ) {
      return item
    }
    return []
  })
})

// 路由跳转事件
const doMenuClick = ({ key }: { key: string }) => {
  router.push({
    path: key,
  })
}

const loginUserStore = useLoginUserStore()

// 用户注销
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  console.log(res)
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败，' + res.data.message)
  }
}

const openMyNotes = () => {
  window.open('/user/myNotes', '_blank')
}

const goToProfile = () => {
  router.push('/user/profile')
}
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: black;
  font-size: 18px;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
